import logging
import urllib

from pyleo.lib.base import *
from pyleo.lib.ping_utilities import *
from pyleo.model.Resource import resource
from paste.request import parse_querystring

log = logging.getLogger(__name__)

class PingController(BaseController):

    def index(self):
        '''Handled ping creation '''
        if  not c.loginStatus:
            response.status_code=401
            return 'not logged in'
        qs=dict(parse_querystring(request.environ))
        try:
            c.path=qs['page']
        except:
            return '<p> Invalid ping source </p>'
        c.source_url=g.site_url+g.home_href+c.path
        c.action='ping/deliver'
        return self.layout_pinger(resource(c.path))
    
    def layout_pinger(self,page):
        ''' Layout the ping (including trackback) delivery form page '''
        
        time = None
        if page.exists():
            rr=page.get()
            c.page_title=rr['title']
            c.html=rr['content']
            parsedPage=PageCandidates(c.html,g.site_url)
            c.addresses=parsedPage.geturls()
        else:
            c.html="Source URL doesn't seem to exist, so no content available for cutting and pasting!"
            c.addresses=[]
        return render('showping')
        
        
    def deliver(self):
        ''' Deliver a ping from the layout page '''
        params=dict(request.params)
        print params
        try:
            doTechnorati=int(params['doTechnorati'])
        except:
            return '<p> Error in POST to pinger (doTechnorati not present or invalid)</p>'
        
        try:
            title=params['page_title']
            blog_name=params['blog_name']
            blog_url=params['blog_url']
            source_url=params['source_url']
        except:
            return '<p> Error in POST to ping (not all compulsory elements present)</p>'
        
        c.pingResults=[]
        
        if doTechnorati:
            pinger=UpdatePinger(blog_name,blog_url,proxyServer=g.proxy_server)
            for url in g.ping_targets.split(','):
                s=pinger.issue(url)
                c.pingResults.append(url,s)
        
        c.tbResults=[]
        try:
            excerpt=params['excerpt_content']
        except: # no excerpts case is dealt with
            excerpt=None
        
        if excerpt:
            targetNumber=int(params['targetNumber'])
            payload={'excerpt': excerpt,'url':source_url,'title':title,'blog_name':blog_name}
            s=urllib.urlencode(payload)
            for i in range(targetNumber):
                #recognising that many may not actually be checked, and therefore passed through ...
                key='target%s'%(i+1)
                key_url='%s-url'%key
                try:
                    target_url=params[key_url]
                    #htmlResponse+='%s<br/>'%target_url
                    try:
                        doit=(params[key]=='on')  # should fail if not checked ..
                    except Exception,e:
                        doit=0 
                    if doit:
                        try:
                            s=TrackbackPing(target_url,s,proxyServer=g.proxy_server)
                        except Exception,e:
                            s='Unexpected Error [%s]'%str(e)
                        c.tbResults.append((target_url,s))
                except Exception,e:
                    target_url=key_url
                    s='Unexpected Error [%s]'%str(e)
                    c.tbResults.append((target_url,s))
        
        return render('pingResult')
 